import axios from 'axios';
import { Message } from 'element-ui';
import baseURL from './baseURL'; // url
import router from '@/router';

// 创建axios实例
const service = axios.create({
  baseURL: baseURL.webServiceUrl
  // withCredentials: true // 跨域请求时发送cookie
  // timeout: 5000 // request timeout
});
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截器
service.interceptors.request.use(
  config => {
    // console.log('请求拦截config',config);
    // if (getToken()) {
    config.headers['satoken'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJwbGF0Zm9ybV91c2VyOjEwMTE4Iiwicm5TdHIiOiJ3bUxoa09UaDdETkhmSzJCZ01WcTlpMExZcUZadGVIQSIsInVzZXJJZCI6MTAxMTh9.6sSggmW6G4j0OnYhaTQfdvCODTwmuQcJmOrKIKVQnuI';
    // }
    return config;
  },
  error => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    // console.log('响应拦截res',res);
    if (res.code !== 200) {
      // 如果501表示token过期，跳转至父系统登录页
      if (res.code === 501) {
        setTimeout(() => {
          router.push({ path: '/login' });
        }, 0);
      } else {
        Message({
          message: res.msg || '出现未知错误，请刷新后重试！',
          type: 'error',
          duration: 3 * 1000
        });
      }
      return Promise.reject(new Error(res.message || res.msg));
    } else {
      return res;
    }
  },
  error => {
    console.log('err' + error); // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    });
    return Promise.reject(error);
  }
);
export default service;
